package project

import (
	"fmt"
	"strings"
	"text/template"

	"github.com/AlecAivazis/survey/v2"
)

func LoadConfigFromCLI() (*Project, error) {
	p := Project{
		render:    template.New("project"),
		createDir: map[string]bool{},
	}
	p.render.Funcs(p.FuncMap())

	err := survey.AskOne(
		&survey.Input{
			Message: "请输入项目包名称:",
			Default: "gitee.com/go-course/mcube-demo",
		},
		&p.PKG,
		survey.WithValidator(survey.Required),
	)
	if err != nil {
		return nil, err
	}

	choicedDB := ""
	choiceDB := &survey.Select{
		Message: "选择数据类型:",
		Options: []string{"MySQL", "MongoDB"},
		Default: "MySQL",
	}

	err = survey.AskOne(choiceDB, &choicedDB)
	if err != nil {
		return nil, err
	}

	switch choicedDB {
	case "MySQL":
		p.EnableMysql = true
		// p
	case "MongoDB":
		p.EnableMongoDB = true
		//
	}

	return nil, nil
}

type Project struct {
	PKG           string   `yaml:"pkg"`
	Name          string   `yaml:"name"`
	Description   string   `yaml:"description"`
	EnableMcenter bool     `yaml:"enable_mcenter"`
	Mcenter       *Mcenter `yaml:"-"`
	EnableMysql   bool     `yaml:"enable_mysql"`
	MySQL         *MySQL   `yaml:"-"`
	EnableMongoDB bool     `yaml:"enable_mongodb"`
	MongoDB       *MongoDB `yaml:"-"`
	GenExample    bool     `yaml:"gen_example"`
	HttpFramework string   `yaml:"http_framework"`
	EnableCache   bool     `yaml:"enable_cache"`

	render    *template.Template
	createDir map[string]bool
}

type Mcenter struct {
	Host         string
	Port         string
	ClientID     string
	ClientSecret string
}
type MySQL struct {
	Host     string
	Port     string
	Database string
	UserName string
	Password string
}
type MongoDB struct {
	Endpoints []string
	UserName  string
	Password  string
	Database  string
	AuthDB    string
}

func (p *Project) FuncMap() template.FuncMap {
	return template.FuncMap{
		"ListToTOML": func(strs []string) string {
			strList := []string{}
			for i := range strs {
				strList = append(strList, fmt.Sprintf(`"%s"`, strs[i]))
			}
			return "[" + strings.Join(strList, ",") + "]"
		},
	}
}
